#!/bin/bash

function readTest() {
    mkdir -p data rd
    rm -rf data/* rd/*

    make clean
    make build

    fileName=wdnmd
    dd if=/dev/urandom of=data/${fileName} bs=4096 count=${1}

    ./evenodd write 5 data/${fileName} ${fileName}
    rm -rf disk_${2} disk_${3}

    ./evenodd read 5 ${fileName} rd/${fileName}

    diff -sr data rd >> result.txt
}

function repair2Test() {
    mkdir -p data rd bak
    rm -rf data/* rd/* bak/*

    make clean
    make build

    fileName=wdnmd
    dd if=/dev/urandom of=data/${fileName} bs=4096 count=${1}

    ./evenodd write 5 data/${fileName} ${fileName}
    mv disk_${2} bak/
    mv disk_${3} bak/

    ./evenodd repair 5 ${2} ${3}

    diff -sr disk_${2} bak/disk_${2} >> result.txt &&\
    diff -sr disk_${3} bak/disk_${3} >> result.txt
}

# set -x

rm -f result.txt
for i in $(seq -w 20); do
    repair2Test ${i} 0 1 && repair2Test ${i} 0 5 &&\
    repair2Test ${i} 1 6 && repair2Test ${i} 5 6
    if [ $? -eq 0 ]; then
        echo "all test passed"
        make clean
    else
        echo "test failed"
        exit 1
    fi
done

for i in $(seq -w 20); do
    readTest ${i} 0 1 && readTest ${i} 0 5 &&\
    readTest ${i} 1 6 && readTest ${i} 5 6
    if [ $? -eq 0 ]; then
        echo "all test passed"
        make clean
    else
        echo "test failed"
        exit 1
    fi
done

rm -rf data/* rd/* bak/*
echo "all test passed"
